import cryptoJs from 'crypto-js';//解密文件
import { DesKey, DesIv } from '../../const/infoConst';
//随机生成指定数量的16进制key
export const generatekey = (num) => {
    let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let key = "";
    for (var i = 0; i < num; i++) {
        let randomPoz = Math.floor(Math.random() * library.length);
        key += library.substring(randomPoz, randomPoz + 1);
    }
    return key;
}
// DES(CBC)加密
export const encryptByCBC = function (message) {
    let key = cryptoJs.enc.Utf8.parse(DesKey);
    let iv = cryptoJs.enc.Utf8.parse(DesIv);
    let srcs = cryptoJs.enc.Utf8.parse(message);
    // 加密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
    let encrypted = cryptoJs.TripleDES.encrypt(srcs, key, {
        iv: iv,
        mode: cryptoJs.mode.CBC,
        padding: cryptoJs.pad.Pkcs7
    });
    return cryptoJs.enc.Base64.stringify(encrypted.ciphertext);   //返回base64
}
// DES(CBC)解密
export const decryptByCBC = function (message) {
    let key = cryptoJs.enc.Utf8.parse(DesKey);
    let iv = cryptoJs.enc.Utf8.parse(DesIv);
    let base64 = cryptoJs.enc.Base64.parse(message);
    let src = cryptoJs.enc.Base64.stringify(base64);
    // 解密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
    let decrypt = cryptoJs.TripleDES.decrypt(src, key, {
        iv: iv,
        mode: cryptoJs.mode.CBC,
        padding: cryptoJs.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(cryptoJs.enc.Utf8);
    return decryptedStr;  //JSON.parse(decryptedStr)
}
export default {
    encryptByCBC,
    decryptByCBC,
}
